import { openForge, openForgeDemo } from "@/api/forge";
import { onBuriedPoint } from "@/api/user";
import { useAuth } from "@/store/auth";
import { useBasic } from "@/store/basic";

import type { CircleSliderInstance } from "./CircleSlider/circleSlider";

export enum OpenForgeType {
  PROD = "spin",
  DEMO = "demo-spin",
}

export const useOpenForge = (
  probability: Ref<number>,
  circleSliderRef: Ref<CircleSliderInstance>
) => {
  const basic = useBasic();
  const route = useRoute();
  const openForgeLoading = ref(false);
  const spinResult = ref<API.Forge.ForgeOpenResponse>();
  const isPlay = ref(false);

  async function onOpenSpin(type: OpenForgeType) {
    const request = type === OpenForgeType.PROD ? openForge : openForgeDemo;
    openForgeLoading.value = true;

    const result = await request({
      id: Number(route.query.forge_id),
      spin_probability: `${probability.value}`,
    });
    type === OpenForgeType.PROD && useAuth().getUserAssets();
    if (result === null) {
      openForgeLoading.value = false;
    } else {
      spinResult.value = result;
      circleSliderRef.value?.startSpin(Number(result.spin_probability), () => {
        openForgeLoading.value = false;
        type === OpenForgeType.PROD && useAuth().getUnprocessedList();
      });

      onBuriedPoint({
        page_name: "forge-详情",
        action: "点击按钮",
        button_name: type,
        box_id: route.query.id as string,
      });
    }
  }

  function onAnimationStart() {
    basic.audio.forgeStartPlay();
  }

  function onAnimationEnd() {
    if (spinResult.value?.spin_result === "1") {
      isPlay.value = true;
      basic.audio.winPlay();
    }
  }

  function onPlayComplete() {
    isPlay.value = false;
  }

  return {
    isPlay,
    openForgeLoading,
    onOpenSpin,
    onAnimationStart,
    onAnimationEnd,
    onPlayComplete,
  };
};
